<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-10-05
 * Time: 12:35
 */

namespace app\common\model;


use app\api\model\op\v1\WXMPShopRequestData;
use app\common\enum\WXMPShopProductStatus;
use app\common\exception\WxMpShopException;

class MpShopProduct extends BaseModel
{

    /**
     * 对主图数据进行json化处理
     * @param $value
     * @param $data
     * @return false|string
     */
    public function setHeadImgsAttr($value, $data)
    {
        if (empty($value)) {
            return json_encode([], JSON_UNESCAPED_UNICODE);
        } else {
            return json_encode($value, JSON_UNESCAPED_UNICODE);
        }
    }

    /**
     * 对主图数据进行解json化处理
     * @param $value
     * @param $data
     * @return array|mixed
     */
    public function getHeadImgsAttr($value, $data)
    {
        if (empty($value)) {
            return [];
        } else {
            return json_decode($value, true);
        }
    }

    /**
     * 对取出的最小价格进行分元转换处理
     * @param $value
     * @param $data
     * @return float|int
     */
    public function getMinPriceAttr($value, $data)
    {
        if (empty($value)) {
            return 0;
        } else {
            return intval($value) / 100;
        }
    }

    /**
     * 获取微信小商店商品的分页数据
     * @param array $params
     * @return \think\Paginator
     */
    public static function getPaginationList(array $params)
    {
        static::validatePaginationData($params);

        $static = new static();

        foreach ($params as $name => $value) {
            $value = !is_array($value) ? trim($value) : $value;
            switch ($name) {
                case 'title':
                    if (!empty($value)) {
                        $like_text = '%' . $value . '%';
                        $static = $static->whereLike('title', $like_text);
                    }
                    break;
                case 'status':
                    if (!empty($value)) {
                        $static = $static->where('status', '=', intval($value));
                    }
                    break;
                case 'edit_status':
                    if (!empty($value)) {
                        $static = $static->where('edit_status', '=', intval($value));
                    }
                    break;
            }
        }

        return $static
            ->paginate([
                'page' => $params['page'],
                'list_rows' => $params['limit']
            ], false);
    }

    /**
     * 获取微信小商店小程序展示内容的分页数据
     * @param array $params
     * @return array
     */
    public static function getMpPaginationList(array $params)
    {

        static::validatePaginationData($params);

        $paginateData = static::where([['status','=',WXMPShopProductStatus::SHELVES]])
            ->order(['product_id'=>'DESC'])
            ->paginate([
                'page' => $params['page'],
                'list_rows' => $params['limit'],
            ],true);

        if ($paginateData->isEmpty()) {
            throw new WxMpShopException();
        }

        return $paginateData->toArray();
    }

    /**
     * 获取微信小商店商品的全部标题信息
     * @return array
     */
    public static function getAllProductTitle()
    {
        $data = static::where([['status','=',WXMPShopProductStatus::SHELVES]])
            ->field(['product_id','title'])
            ->select();

        return !empty($data) ? $data->toArray(): [];
    }

    /**
     * 从微信服务器获取数据到本地服务器的数据库中
     */
    public static function updateProductFormWX()
    {
        $page = 1;
        $page_size = 10;

        $static = new static();
        $static->startTrans();
        try {
            // 先清空旧数据
            $static->whereRaw('1=1')
                ->delete();

            // 获取微信服务器的数据
            $save_data = [];
            do {
                $wx_server_data = (new WXMPShopRequestData('product'))->getProductList($page, $page_size);
                foreach ($wx_server_data as $product_data) {
                    $save_data[] = [
                        'product_id' => $product_data['product_id'],
                        'title' => $product_data['title'],
                        'head_imgs' => $product_data['head_img'],
                        'min_price' => $product_data['min_price'],
                        'status' => $product_data['status'],
                        'edit_status' => $product_data['edit_status']
                    ];
                }
                $page++;
            } while(!empty($wx_server_data));

            $static->saveAll($save_data);

            $static->commit();
        } catch (\Exception  $e) {
            $static->rollback();
            return false;
        }

        return true;
    }
}